<?php
namespace frontend\controllers;

use common\models\Category;
use common\models\Post;
use common\Yii01;
use Yii;
use yii\base\InvalidParamException;
use yii\data\Pagination;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    /*public function actionIndex()
    {
        return $this->render('index');
    }*/
    public function actionIndex($type = null)
    {

        $query = Post::find()->joinWith('cate');

        if ($type == null) {
            // $sql ="SELECT *,post.view*10+post.zan*3+post.cai num FROM post  JOIN category AS cate ON post.cate_id = cate.id WHERE post.status IN (1, 2, 4) ORDER BY post.status DESC,num DESC";
            $sql = "SELECT *,(post.zan-post.cai)/(POW((unix_timestamp(now())-post.create_at)/3600+2,1.5)) num FROM post WHERE post.status IN (1, 2, 4) ORDER BY post.status DESC,num DESC";
            $q = Yii::$app->db->createCommand($sql)->queryAll();
            $pages = new Pagination([
                'totalCount' => count($q),
                'defaultPageSize' => 20
            ]);
            $model = Yii::$app->db->createCommand($sql . " limit " . $pages->limit . " offset " . $pages->offset . "")->queryAll();

            $temp = [];
            foreach ($model as $v) {
                $temp1 = $v;
                $temp2['cate'] = Category::findOne(['id' => $v['cate_id']])->toArray();
                $temp[] = array_merge($temp1, $temp2);
            }

            $model = $temp;
        } elseif ($type == "article") {
            $post = $query->orderBy(['post.id' => SORT_DESC])->asArray()->where(['type' => 1, 'post.status' => 1]);
            $pages = new Pagination([
                'totalCount' => $post->count(),
                'defaultPageSize' => 20
            ]);
            $model = $post->offset($pages->offset)->limit($pages->limit)->all();
        } elseif ($type == "zy") {
            $post = $query->orderBy(['post.status' => SORT_DESC, 'post.cai' => SORT_DESC])->asArray()->where(['post.status' => [1, 2, 4]]);
            $pages = new Pagination([
                'totalCount' => $post->count(),
                'defaultPageSize' => 20
            ]);
            $model = $post->offset($pages->offset)->limit($pages->limit)->all();
        } elseif ($type == "pic") {
            $post = $query->orderBy(['post.last_comment' => SORT_DESC])->asArray()->where(['type' => 2, 'post.status' => 1]);
            $pages = new Pagination([
                'totalCount' => $post->count(),
                'defaultPageSize' => 20
            ]);
            $model = $post->offset($pages->offset)->limit($pages->limit)->all();
        } elseif ($type == "url") {
            $post = $query->orderBy(['post.last_comment' => SORT_DESC])->asArray()->where(['type' => 3, 'post.status' => 1]);
            $pages = new Pagination([
                'totalCount' => $post->count(),
                'defaultPageSize' => 20
            ]);
            $model = $post->offset($pages->offset)->limit($pages->limit)->all();
        } elseif ($type == "new") {
            $post = $query->orderBy(['post.status' => SORT_DESC, 'post.id' => SORT_DESC])->asArray()->where(['post.status' => [1, 2, 4]]);
            $pages = new Pagination([
                'totalCount' => $post->count(),
                'defaultPageSize' => 20
            ]);
            $model = $post->offset($pages->offset)->limit($pages->limit)->all();
        } else {
            throw new BadRequestHttpException("参数错误！");
        }

        //将结果传递到视图
        //    WuMing::dd($model);die;

        $title = Yii01::getSiteInfo("site-name")->value;
        $keywords = Yii01::getSiteInfo("site-keywords")->value;
        $description = Yii01::getSiteInfo("site-description")->value;
        return $this->render('index', [
            'model' => $model,
            'pages' => $pages,
            'type' => $type,
            'title' => $title,
            'keywords' => $keywords,
            'description' => $description,
            'active' => true,
        ]);
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect(Yii::$app->urlManager->createUrl("focus/index"));
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->redirect("login");
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->redirect(Yii::$app->urlManager->createUrl("list/index"));
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
}
